package fi.iki.joker.mobilogger;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import fi.iki.joker.mobilogger.db.BlogEntryBean;
import fi.iki.joker.mobilogger.db.DBUtil;
import fi.iki.joker.mobilogger.util.AlertUtil;

/**
 * Lists the blog entries that are stored locally and allows user to modify and delete them. 
 * @author juhak
 *
 */

public class ListBlogEntries extends Activity implements 
	AdapterView.OnItemSelectedListener,
	AdapterView.OnItemClickListener {
	
	private int currentlySelectedItem = -1;
	private int tabsHeight = 0;
	private DBUtil db = null;
	private String [] listData = null;
	private ListView list = null;
	private final String TAG = "ListBlogConfigs";
	
	public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.managedata);
        TextView tv = (TextView) findViewById(R.id.selected_button_view);
        tv.setText("Please select an entry from the list");
        ButtonBar.createButtons(this);
        ButtonBar.requestFocusForButton(ButtonBar.BUTTON_BLOG_ENTRIES);
        list = (ListView)findViewById(R.id.shown_data_list);
        updateListData(list);
        list.setOnItemSelectedListener(this);
        list.setOnItemClickListener(this);
    }
	
	private void updateListData(ListView list) {
		if(db == null) {
        	db = new DBUtil();
        }
		BlogEntryBean[] tempArr = db.getBlogEntries(this.getApplication());
		if(tempArr != null) {
			list.setVisibility(View.VISIBLE);
			listData = new String[tempArr.length];
			for(int i = 0; i < tempArr.length; i++) {
				BlogEntryBean bc = tempArr[i];
				int id = bc.getId();
				if(bc == null) {
						listData[i] = "null";
        			} else {
        				listData[i] = new String("["+id+"]"+bc.toString());
        			}
			}
			list.setAdapter(new ArrayAdapter<String>(this, 
					android.R.layout.simple_list_item_1,listData));	
		} else {
			list.setVisibility(View.INVISIBLE);
		}
    }
	
	public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		this.currentlySelectedItem = arg2;
	}

	public void onNothingSelected(AdapterView arg0) {
		this.currentlySelectedItem = 0;
	}
	
	public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
		this.currentlySelectedItem = arg2;
		AlertUtil.showAlert(this,"Select operation","What do you want to do?", "Edit", 
				mEditListener, "Delete", mDeleteListener);
	}

	
	OnClickListener mEditListener = new OnClickListener() {
    public void onClick(DialogInterface df, int item) {
        editEntry(getEntryId(listData[currentlySelectedItem]));
    	}
	};
	
    OnClickListener mDeleteListener = new OnClickListener() {
        public void onClick(DialogInterface df, int item) {
            deleteEntry(getEntryId(listData[currentlySelectedItem]));
            updateListData(list);
        }
    };
	
    private void editEntry(int entryId) {
    	Intent intent = new Intent();
		intent.setClass(this, BlogEntryEditor.class);
		intent.setAction(Intent.ACTION_EDIT);
		String URIStr = "content://fi.iki.joker.mobilogger/blogentry/"+entryId;
		intent.setData(Uri.parse(URIStr));
		this.startActivity(intent);
		this.finish();
    }
    
    private void deleteEntry(int entryId) {
    	if(db != null) {
    		db.deleteBlogEntryItem(this,entryId);
    	} else {
    		Log.e(TAG,"Database not ready while deleting blog entry.");
    	}
    }
    
    /**
     * This is ugly, we get the id from the [num]-Title,
     * should probably be done otherwise but this is simple
     */
    
    private int getEntryId(String entryTitle) {
    	if(entryTitle == null) return -1;
    	int start = 1; // the [
    	int end = entryTitle.indexOf(']');
    	String number = entryTitle.substring(start, end);
    	int res = -1;
    	try {
    		res = Integer.parseInt(number);
    	} catch (NumberFormatException e) {
    		Log.e(TAG,"Error parsing entry ID out of String: "+entryTitle+" Start: "+start+" End: "+end);
    		return -1;
    	}
    	return res; 
    }
}
